"""

    异步上下文管理

"""
import asyncio
import socket
from types import TracebackType
from typing import Optional, Type


class ConnectedSocket:
    def __init__(self, server_socket):
        self._connection = None
        self._server_socket = server_socket

    async def __aenter__(self):
        print("进入上下文管理器，等待连接")
        loop = asyncio.get_event_loop()
        connection, address = await loop.sock_accept(self._server_socket)
        self._connection = connection
        print("接收到一个请求")
        return self._connection

    async def __aexit__(self,
                        exc_type: Optional[Type[BaseException]],
                        exc_val: Optional[BaseException],
                        exc_tb: Optional[TracebackType]):
        print("退出上下文管理器")
        self._connection.close()
        print("关闭连接")


async def main():
    loop = asyncio.get_event_loop()
    # 创建一个TCP服务器套接字
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    #  将SO_REUSEADDR 设置为1，表示重复使用此端口，避免出现address already In use错误。
    server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    # 将套接字的地址设置为127.0.0.1:8000
    address = ("127.0.0.1", 8000)
    server_socket.setblocking(False)
    server_socket.bind(address)
    # 开启监听传入的连接
    server_socket.listen()

    async with ConnectedSocket(server_socket) as connection:
        data = await loop.sock_recv(connection, 1024)
        print(data)


asyncio.run(main())
